package edu.ncst.baseweb.service.impl.resinfo;

import cn.wintersun.basecommon.common.Result;
import edu.ncst.baseweb.dao.ResList;
import edu.ncst.baseweb.dao.User;
import edu.ncst.baseweb.dao.res.ResInfo;
import edu.ncst.baseweb.mapper.ResInfoMapper;
import edu.ncst.baseweb.service.intrer.resinfo.ResExamineeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

//预约审批
@Service
public class ResExamineImpl implements ResExamineeService {
    @Autowired
    private ResInfoMapper resInfoMapper;

    public Result<IPage<ResInfo>> list(ResInfo resInfo){
        QueryWrapper<ResInfo> queryWrapper = Wrappers.query();

        //实验名称查询
        if(StringUtils.isNotEmpty(resInfo.getTiliteName())){
            queryWrapper.like(ResInfo.COL_TILITENAME,resInfo.getTiliteName());
        }
        queryWrapper.eq(ResInfo.COL_STATE,"0");
        Page<ResInfo> resPage = new Page<>(resInfo.getCurrent(), resInfo.getPageSize());
        Page<ResInfo> resInfoPage = resInfoMapper.selectPage(resPage, queryWrapper);

        List<ResInfo> resInfos = resInfoPage.getRecords();
        for (ResInfo resInfo1: resInfos){
            //查询有几个人预约了
            resInfo1.setPeople(resInfoMapper.countRecordsByResId(resInfo1.getId()));
            resInfoMapper.updateById(resInfo1);
        }
        System.out.println();

        return Result.ok(resInfoPage);
    }
    //审批
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> examine(ResInfo resInfo) throws Exception {
        if(resInfo.getState()==1){
            resInfoMapper.updateStateById(resInfo.getId(),1);
        }else if (resInfo.getState()==2){
            resInfoMapper.updateStateById(resInfo.getId(),2);
        }else {
            return Result.failure(500, "审批失败");
        }

        return Result.failure(200, "成功！");
    }
    @Override
    public Result<List<ResList>> getResList(ResInfo resInfo) {
        //创捷列表
        List<ResList> resLists = new ArrayList<>();
        List<String> ids = resInfoMapper.getUserIdsByResId(resInfo.getId());
        System.out.println(ids);
        System.out.println("1234");

        for (String id1: ids){
            User user1 = resInfoMapper.getUsersByIds(id1);
            resLists.add(new ResList(user1.getUserName(),user1.getNumber(),user1.getPhone()));
        }

        return Result.ok(resLists);
    }
}
